package com.soar.recruitment.module.web.bll;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.soar.recruitment.common.ui.view.SOARWebView;
import com.soar.recruitment.common.util.NetworkUtil;
import com.soar.recruitment.module.web.bll.constants.SOARWebConstants;
import com.soar.recruitment.module.web.bll.interfaces.IBaseWeb;
import com.soar.recruitment.module.web.bll.interfaces.OnWebLoadListener;
import com.soar.recruitment.module.web.bll.interfaces.OnWebTitleListener;
import com.soar.recruitment.module.web.bll.web.SOARWebChromeClient;
import com.soar.recruitment.module.web.bll.web.SOARWebJSBridge;
import com.soar.recruitment.module.web.bll.web.SOARWebViewClient;


public class SOARWebController implements IBaseWeb {

    private Activity mActivity;
    private LinearLayout mWebViewLayout;
    private SOARWebView mWebView;
    private SOARWebJSBridge mKFQWebJSBridge;

    private boolean isOnPause = false;
    private boolean mIsHome;

    public SOARWebController(Activity activity, FragmentManager fragmentManager, LinearLayout linearLayout, OnWebTitleListener onWebTitleListener, OnWebLoadListener onWebLoadListener) {
        this.mActivity = activity;
        this.mWebViewLayout = linearLayout;
        this.mIsHome = false;
        initWebView(onWebTitleListener, onWebLoadListener, fragmentManager);
    }

    public SOARWebController(Activity activity, FragmentManager fragmentManager, LinearLayout linearLayout, OnWebTitleListener onWebTitleListener, OnWebLoadListener onWebLoadListener, boolean isHome) {
        this.mActivity = activity;
        this.mWebViewLayout = linearLayout;
        this.mIsHome = isHome;
        initWebView(onWebTitleListener, onWebLoadListener, fragmentManager);
    }

    private void initWebView(OnWebTitleListener onWebTitleListener, OnWebLoadListener onWebLoadListener, FragmentManager fragmentManager) {
        if (mWebView == null) {
            mWebView = new SOARWebView(mActivity);
            mWebView.init();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
                mWebView.removeJavascriptInterface("accessibility");
                mWebView.removeJavascriptInterface("accessibilityTraversal");
            }
            initWebViewClient(onWebLoadListener);
            initWebChromeClient(onWebTitleListener);
            initJSBridge(fragmentManager);
        }
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)mWebViewLayout.getLayoutParams();
        mWebViewLayout.addView(mWebView, params.width, params.height);

    }

    public SOARWebView getWebView() {
        if(mWebView != null) {
            return mWebView;
        }
        return null;
    }

    private void initWebViewClient(final OnWebLoadListener onWebLoadListener) {
        mWebView.setWebViewClient(new SOARWebViewClient(new OnWebLoadListener() {
            @Override
            public void showContent() {
                if (onWebLoadListener != null) {
                    onWebLoadListener.showContent();
                }
            }

            @Override
            public void showError() {
                if (onWebLoadListener != null) {
                    onWebLoadListener.showError();
                }
            }
        }));
    }

    private void initWebChromeClient(final OnWebTitleListener onWebTitleListener) {
        mWebView.setWebChromeClient(new SOARWebChromeClient(new OnWebTitleListener() {
            @Override
            public void onReceivedTitle(String title) {
                if(onWebTitleListener != null) {
                    onWebTitleListener.onReceivedTitle(title);
                }
            }

            @Override
            public void progressChanged(int newProgres) {
                if(onWebTitleListener != null) {
                    onWebTitleListener.progressChanged(newProgres);
                }
            }
        }));
    }

    private void initJSBridge(FragmentManager fragmentManager) {
        mKFQWebJSBridge = new SOARWebJSBridge(mActivity, fragmentManager);
        mWebView.addJavascriptInterface(mKFQWebJSBridge, SOARWebConstants.JS_FLAG);
    }

    @Override
    public void onLoadUrl(final String url) {
        if (mWebView != null) {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl(url);
                }
            });
        }
    }

    @Override
    public void onReloadView() {
        if (mWebView != null) {
            mWebView.reload();
        }
    }


    @Override
    public void onGoBack() {
        if (mWebView == null) {
            return;
        }
        if (isCanGoBack() && NetworkUtil.isNetworkAvailable(mActivity)) {
            mWebView.goBack();
        } else {
            pageFinish();
        }
    }

    public void onWebViewGoBack() {
        if (mWebView != null) {
            mWebView.goBack();
        }
    }

    public void webviewBack() {
        if (mWebView != null) {
            mWebView.goBack();
        }
    }

    /**
     * 是否能返回
     * @return
     */
    public boolean isCanGoBack() {
        if(mWebView == null) {
            return false;
        } else {
            return mWebView.canGoBack();
        }
    }

    @Override
    public void onResume() {
//        if (mWebView != null) {
//            mWebView.resumeTimers();
//        }
        try {
            if (isOnPause) {
                if (mWebView != null) {
                    mWebView.getClass().getMethod("onResume").invoke(mWebView, (Object[]) null);
                }
                isOnPause = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        try {
            if (mWebView != null) {
                // Pauses all layout, parsing, and JavaScript timers for all WebViews. Thisis a global requests, not restricted to just this WebView. This can beuseful if the application has been paused.
                //mWebView.pauseTimers();
                if (mActivity.isFinishing()) {
                    mWebView.loadUrl(SOARWebConstants.BLANK_LOADING);
                }
                mWebView.getClass().getMethod("onPause").invoke(mWebView, (Object[]) null);
                isOnPause = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestory() {
        mKFQWebJSBridge.doDestory();
        if (mWebView != null) {
            mWebView.clearCache(true); //清空缓存
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (mWebViewLayout != null) {
                    mWebViewLayout.removeView(mWebView);
                }
                webViewDestory();
            }else {
                webViewDestory();
                if (mWebViewLayout != null) {
                    mWebViewLayout.removeView(mWebView);
                }
            }
            mWebView = null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Bundle data) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mKFQWebJSBridge.doActivityResult(requestCode, resultCode, data);
    }

    private void webViewDestory() {
        try {
            mWebView.stopLoading();
        } catch (Throwable ignored) {

        }
        try {
            mWebView.removeAllViews();
        } catch (Throwable ignored) {

        }
        try {
            mWebView.setWebChromeClient(null);
        } catch (Throwable ignored) {

        }
        try {
            mWebView.setWebViewClient(null);
        } catch (Throwable ignored) {

        }
        try {
            mWebView.destroy();
        } catch (Throwable ignored) {

        }
    }

    private void pageFinish() {
        mActivity.finish();
    }

}
